import store from '../store/index.js'
// const wxUrl = "ws://119.29.67.157:9002/ws/PkCentre"
// const wxUrl = "ws://127.0.0.1:18090/ws/pkCentre"
const wxUrl = "ws://159.75.228.168:18090/ws/pkCentre"
const basicUrl = "https://gateway.xiaohong.work/api/saolei"
// const basicUrl = "http://localhost:18090"
// const basicUrl = "http://119.29.67.157:9002"
var lastTime = 0
var LastType = ""
// const basicUrl = "http://119.29.67.157:9002"
var socketTask = {}
var message = {
	sender: "",
	receiver: "",
	content: '',
	sendTime: new Date().getTime(),
	type: '',
	heart: false
}
var websocket_isOpen = false
var try_count = 0 // 尝试次数
var lastReceiverTime = 0
var startTimeId = null
var settimeid = []

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

var dateFormat = function (timestamp, formats) {
    // formats格式包括
    // 1. Y-m-d
    // 2. Y-m-d H:i:s
    // 3. Y年m月d日
    // 4. Y年m月d日 H时i分
    formats = formats || 'Y-m-d';

    var zero = function (value) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };

    var myDate = timestamp? new Date(timestamp): new Date();

    var year = myDate.getFullYear();
    var month = zero(myDate.getMonth() + 1);
    var day = zero(myDate.getDate());

    var hour = zero(myDate.getHours());
    var minite = zero(myDate.getMinutes());
    var second = zero(myDate.getSeconds());

    return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
        return ({
            Y: year,
            m: month,
            d: day,
            H: hour,
            i: minite,
            s: second
        })[matches];
    });
};

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
}

// 将rpx转px
function sizeDeal (size) {
	const info = uni.getSystemInfoSync()
	let scale = 750 / info.windowWidth;
	// 分离字体大小和单位,rpx 转 px
	let s = Number.isNaN(parseFloat(size)) ? 0 : parseFloat(size)
	let u = size.toString().replace(/[0-9]/g, '').replace('-', '')
	if (u == 'rpx') {
		s /= scale
		u = 'px'
	} else if (u == '') {
		u = 'px'
	} else if (u == 'vw') {
		u = 'px'
		s = s / 100 * 750 / scale
	}
	return [s, u, s + u]
}

//生成从minNum到maxNum的随机数
function randomNum(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
            break; 
    } 
} 

//生成指定个数的随机数
function produceRandomNum(size,max){
	var result = []
	while(result.length < size){
		// 基本均衡获取 0 到 max 的随机整数，其中获取最小值 0 和最大值 10 的几率少一半。
		var random = Math.round(Math.random()*max);   
		// 判断是否已添加
		if(result.indexOf(random) == -1){
			// 没添加
			result.push(random)
		}
	}
	
	return result.sort()
} 

// 计算周围炸弹数量
function calculateBombNumber(i,cl,bombs){
	var num = 0
	var id = parseInt(i)
	var colum = parseInt(cl)
	if( (id+1)%colum != 0 && (id+1) < colum*colum && bombs.indexOf(id+1) != -1){
		num ++
	}
	if( id-1 >= 0 && id%colum != 0 && bombs.indexOf(id-1) != -1){
		num ++
	}
	if( id-colum >= 0 && bombs.indexOf(id-colum) != -1){
		num ++
	}
	if( id-colum+1 >= 0 && (id-colum+1)%colum != 0 && bombs.indexOf(id-colum+1) != -1){
		num ++
	}
	if( id-colum-1 >= 0 && (id-colum)%colum != 0 && bombs.indexOf(id-colum-1) != -1){
		num ++
	}
	if( id+colum < colum*colum && bombs.indexOf(id+colum) != -1){
		num ++
	}
	if( id+colum+1 < colum*colum && (id+colum+1)%colum != 0 && bombs.indexOf(id+colum+1) != -1){
		num ++
	}
	if( id+colum-1 < colum*colum && (id+colum)%colum != 0  && bombs.indexOf(id+colum-1) != -1){
		num ++
	}
	return num
}


// 进入页面的时候创建websocket连接【整个页面随时使用】
function connectSocketInit() {
	if(!uni.getStorageSync("saolei_userInfo")){
		console.log("未登录")
		return
	}
	console.log("重新连接")
	// console.log(wxUrl+"/"+uni.getStorageSync("saolei_userInfo").id)
	socketTask = uni.connectSocket({
		url: wxUrl+"/"+uni.getStorageSync("saolei_userInfo").id,
		success(data) {
			// console.log("websocket连接成功");
		}
	});
	
	// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
	socketTask.onOpen((res) => {
		// console.log("WebSocket连接正常打开中...！");
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		websocket_isOpen =  true
		start()
		// 注：只有连接正常打开中 ，才能正常收到消息
		socketTask.onMessage((res) => {
			// console.log("连接成功并收到服务器内容：");
			var rd = JSON.parse(res.data)
			
			// console.log(rd)
			if(rd.heart == false){
				// 除去重复消息
				console.log(rd)
				if(lastTime == rd.sendTime && LastType == rd.type){
					console.log('同一条消息')
					return 
				}else{
					lastTime = rd.sendTime
					LastType = rd.type
					// 判断消息类型
					if(rd.type == "pk_invite"){
						// 邀请信息 获取挑战者消息 弹窗提示
						getFriendInfo(rd.sender)
						store.commit("setPkInfo",JSON.parse(rd.content))
					}else if(rd.type == "pk_over"){
						// 邀请超时信息 获取挑战者资料
						uni.$emit("pk-overTime",new Date())
					}else if(rd.type == "pk_cancel"){
						// 邀请撤销信息 获取撤销者资料
						uni.showToast({
							icon:"none",
							title:"对方已取消"
						})
						store.commit("removeMsgList",rd.sender)
					}else if(rd.type == "pk_agree"){
						// 邀请被同意 获取挑战者消息
						uni.$emit("pk-agreePk",rd.content,new Date())
					}else if(rd.type == "pk_refuse"){
						// 邀请被拒绝信息 获取挑战者消息 弹窗提示
						uni.$emit("pk-refusePk",new Date())
					}else if(rd.type == "pk_message"){
						// pk中发送的信息
						uni.$emit("pk-message",parseInt(JSON.parse(rd.content)))
					}else if(rd.type == "pk_fail_message"){
						// 对手pk失败信息
						uni.$emit("pk-success",new Date())
					}else if(rd.type == "pk_success_message"){
						// 对手pk胜利信息
						uni.$emit("pk-fail",new Date())
					}else if(rd.type == "pk_run_message"){
						// 对手pk逃跑信息
						uni.$emit("pk-run",new Date())
					}else{
						console.log("收到未知消息：")
						console.log(rd)
					}
				}
				
			}else{
				// 心跳消息
				uni.hideLoading()
				// console.log("心跳消息来了！")
				settimeid.forEach(st => {
					clearTimeout(st)
				})
				settimeid = []
				websocket_isOpen = true
			}
		});
	})
	// 这里仅是事件监听【如果socket关闭了会执行】
	socketTask.onClose(() => {
		websocket_isOpen = false
		console.log("连接关闭了")
	})
}

//开启定时心跳检测
function start(){
	var st = setInterval(function(){
		if(uni.getStorageSync("saolei_userInfo") == ""){
			console.log("未登录")
		}else{
			websocket_isOpen = false
			message.sender = uni.getStorageSync("saolei_userInfo").id
			message.receiver = uni.getStorageSync("saolei_userInfo").id
			message.sendTime = new Date()
			message.heart = true
			message.type = ""
			setTimeout(() => {
				socketTask.send({
					data: JSON.stringify(message),
					async success() {
						
					},
				});
			}, 500)
		}
	},5000)
	
	store.commit("setStartTimeId",st)
}

//重新连接
function reconnect(){
	//如果不是人为关闭的话，进行重连
	if (!store.state.is_open_socket) {
		// 最多尝试五次
		if(store.state.socket_try_count <= 5){
			console.log('连接断开，重连中。。')
			store.commit('addTryCount')
			setTimeout(() => {
				connectSocketInit();
			}, 1000)
		}else{
			// 关闭重连标识
			store.commit('closeTryFlag')
		}
	}else{
		// this.socket_try_count = 0
		// console.log('连接没问题！')
	}
}

// 关闭websocket【离开这个页面的时候执行关闭】
function closeSocket(){
 	if(store.state.start_timeId){
		clearInterval(store.state.start_timeId)
		store.commit("setStartTimeId",null)
		socketTask.close({
			success(res) {
				console.log("关闭成功", res)
			},
			fail(err) {
				console.log("关闭失败", err)
			}
		})
	}
}

// 发送消息
function send(msg){
	msg.heart = false
	msg.sendTime = new Date()
	
	setTimeout(() => {
		socketTask.send({
			data: JSON.stringify(msg),
			async success() {
				console.log("普通消息发送成功");
				console.log(msg)
			},
		});
	}, 500)
}

// 获取用户资料
function getFriendInfo(id){
	uni.request({
		url: basicUrl+"/saoleiUser/"+id,
		method: "GET",
		data: {},
		success: function(res) {
			if(res.data.code === 20000){
				store.commit("setOpponet",res.data.data)
				addPopMessage(res.data.data)
			}else{
				uni.showToast({
					icon:"none",
					title: res.data
				})
			}
		},
		fail: () => {
			uni.showToast({
				icon:"none",
				title: '网络错误'
			})
		},
		complete() {
			uni.hideLoading()
		}
	})
}

// 设置用户状态
function setUserPkStatus(flag){
	uni.request({
		url: basicUrl+'/saoleiUser/pkStatus/'+uni.getStorageSync("saolei_userInfo").id+"/"+flag,
		method: "POST",
		data: {},
		success: function(res) {
			if(res.data.code === 20000){
			}else{
				uni.showToast({
					icon:"none",
					title: res.data,
					position:"center"
				})
			}
		},
		fail: () => {
			uni.showToast({
				icon:"none",
				title: '网络错误(￣▽￣)"',
				position:"center"
			})
		},
		complete() {
			
		}
	})
}

// 添加弹窗消息
function addPopMessage(info){
	var msg = {
		type:'default', //String 默认default
		msg:'好友发来通知', //String 显示内容 *
		direction:'top', //String 默认顶部显示
		icon:true, //Boolean|String 显示icon(false/true/string 默认显示icon)
		mask:false, //Boolean 遮罩（默认false没有遮罩）
		time: 10000,
		customStyle:{ //自定义样式
			color:'#FFFFFF', //字体图标色
			backgroundColor:'rgba(0,0,0,.5)' //背景色
		}, 
		opponetInfo: info,
		iconSize: 16, //Number 自定义icon大小(单位px 默认16 设置后会覆盖自定义样式里的设置优先级最高)
		iconColor: '', //String icon颜色(默认主题颜色 设置后会覆盖自定义样式里的设置优先级最高)
	}
	store.commit("addMsgList",msg)
}

// 弹窗同意
function popAgree(item,time){
	store.commit("setOpponet",item.opponetInfo)
	message.content = uni.getStorageSync("saolei_userInfo").id
	message.sender = uni.getStorageSync("saolei_userInfo").id
	message.receiver = item.opponetInfo.id
	message.type = "pk_agree"
	message.sendTime = time
	send(message)
	setTimeout(function(){
		uni.navigateTo({
			url:"../pk/pk?role=receiver",
			animationDuration: 500,
			animationType:"slide-in-left"
		})
	},800)
	
}

// 弹窗拒绝
function popRefuse(item,time){
	message.sender = uni.getStorageSync("saolei_userInfo").id
	message.receiver = item.opponetInfo.id
	message.type = "pk_refuse"
	message.sendTime = time
	send(message)
}

// 弹窗超时
function popOverTime(item,time){
	message.sender = uni.getStorageSync("saolei_userInfo").id
	message.receiver = item.opponetInfo.id
	message.type = "pk_over"
	message.sendTime = time
	send(message)
}

// 取消邀请
function cancelInvite(item,time){
	message.sender = uni.getStorageSync("saolei_userInfo").id
	message.receiver = item.id
	message.type = "pk_cancel"
	message.sendTime = time
	send(message)
}

// 请求失败错误处理中心
function requestFail (res) {
	// 令牌失效错误
	if(res.statusCode == 401){
		uni.showToast({
			icon:"none",
			title:"权限不足！"
		})
	}else if(res.statusCode == 404){
		uni.showToast({
			icon:"none",
			title:"未找到该服务请求！"
		})
	}else if(res.statusCode == 413){
		uni.showToast({
			icon:"none",
			title:"文件上传最大为1G"
		})
	}else if(res.statusCode == 444){
		// 限流
		uni.showToast({
			icon:"none",
			title:JSON.stringify(res.data)
		})
	}else if(res.statusCode == 500){
		uni.showToast({
			icon:"none",
			title:"后台错误！"
		})
	}else if(res.statusCode == 502){
		uni.showToast({
			icon:"none",
			title:"后台服务未启动！"
		})
	}else if(res.statusCode == 503){
		uni.showToast({
			icon:"none",
			title:"后台服务未启动！"
		})
	}else{
		uni.showToast({
			icon:"none",
			title:"其他错误，错误内容："+JSON.stringify(res.data)
		})
	}
	
}

module.exports = {
	formatTime,
	formatLocation,
	dateUtils,
	sizeDeal,
	randomNum,
	produceRandomNum,
	calculateBombNumber,
	dateFormat,
	connectSocketInit,
	closeSocket,
	basicUrl,
	send,
	getFriendInfo,
	popAgree,
	popRefuse,
	popOverTime,
	cancelInvite,
	setUserPkStatus,
	start,
	startTimeId,
	try_count,
	requestFail
}
